package com.cwb.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author 27435
 * @Date 2025/1/710:31
 * @Version 1.0
 */

@Controller
public class UploadController {

    @Autowired
    private ServletContext servletContext;

    @RequestMapping("/up")
    public String fileUpload(MultipartFile file, Model model) throws IOException {
        System.out.println("--------------------------------------------------");
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String exName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = fileName + exName;
        String virtualPath = "/upload";
        String realPath = servletContext.getRealPath(virtualPath);
        File filePath = new File(realPath, newFileName);
        if (!filePath.getParentFile().exists()){
            filePath.getParentFile().mkdirs();
        }
        file.transferTo(filePath);
        String picPath = servletContext.getContextPath() + "/upload/" + newFileName;
        model.addAttribute("filePath", picPath);
        return "success";
    }

}
